package pers.qianyu.month_202012.date_20201207;

import java.util.*;
import java.util.stream.*;

/**
 * 861. 翻转矩阵后的得分
 * https://leetcode-cn.com/problems/score-after-flipping-matrix/
 *
 * @author mizzle rain
 * @date 2020-12-07 14:04
 */
public class MatrixScore {
    public int matrixScore(int[][] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        for (int i = 0; i < A.length; i++) {
            int[] arr = A[i];
            if (arr[0] != 1) {
                changeRow(arr);
            }
        }
        int height = A.length;
        int width = A[0].length;
        for (int i = 1; i < width; i++) {
            int count1 = 0;
            int count0 = 0;
            for (int k = 0; k < height; k++) {
                if (A[k][i] == 1) {
                    count1++;
                } else {
                    count0++;
                }
            }
            if (count0 > count1) {
                changeColumn(A, i);
            }
        }
        //Arrays.stream(A).forEach(i -> System.out.println(Arrays.toString(i)));
        return sum(A);
    }

    private void changeColumn(int[][] arr, int col) {
        for (int i = 0; i < arr.length; i++) {
            arr[i][col] = arr[i][col] == 1 ? 0 : 1;
        }
    }

    private void changeRow(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] == 1 ? 0 : 1;
        }
    }

    private int sum(int[][] arr) {
        int res = 0;
        for (int i = 0; i < arr.length; i++) {
            res += Integer.parseInt(Arrays.stream(arr[i])
                    .boxed()
                    .map(String::valueOf)
                    .collect(Collectors.joining("")), 2);
        }
        return res;
    }

    public static void main(String[] args) {
        int[][] arr = {
                {0, 0, 1, 1},
                {1, 0, 1, 0},
                {1, 1, 0, 0}
        };
        int result = new MatrixScore().matrixScore(arr);
        System.out.println("result = " + result);
    }
}
